import functools
import re
import socket
import sys

import requests
import socks


def mycmp1(x, y):  # 升序排列
    return x["tStartMs"] - y["tStartMs"]


def cues_cmp1(x, y):  # 升序排列
    return x["cues"][0]["time"] - y["cues"][0]["time"]


def cues_cmp2(x, y):  # 升序排列
    return x["time"] - y["time"]


def down_load_translate(id, name):
    cn_url = f"https://www.youtube.com/api/timedtext?v={id}&lang=zh-CN&fmt=json3"
    en_url = f"https://www.youtube.com/api/timedtext?v={id}&lang=en&fmt=json3"

    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 "
                      "(KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36",
    }

    proxie = {"http": "http://127.0.0.1:2087"}

    en_res = requests.get(en_url, headers=headers, proxies=proxie)
    cn_res = requests.get(cn_url, headers=headers, proxies=proxie)

    en_events = en_res.json()["events"]
    en_events.sort(key=functools.cmp_to_key(mycmp1))

    cn_events = cn_res.json()["events"]
    cn_events.sort(key=functools.cmp_to_key(mycmp1))
    if cn_events[0]["tStartMs"] == 0:
        del (cn_events[0])

    cn_events_new = []
    a = 0
    if len(en_events) - len(cn_events) != 0:
        print("not equal")
        for i in range(len(en_events)):
            en_end = en_events[i]["tStartMs"] + en_events[i]["dDurationMs"]
            cn_text = ""
            while a < len(cn_events) and (cn_events[a]["tStartMs"] - en_end) < -1000:
                if cn_text != "":
                    cn_text += ","
                cn_text += cn_events[a]["segs"][0]["utf8"]
                a += 1
            if cn_text == "":
                cn_text = en_events[i]["segs"][0]["utf8"]
            cn_e = {}
            cn_e["segs"] = [{"utf8": ""}]
            cn_e["segs"][0]["utf8"] = cn_text
            cn_e["tStartMs"] = en_events[i]["tStartMs"]
            cn_e["dDurationMs"] = en_events[i]["dDurationMs"]
            cn_events_new.append(cn_e)
        if len(en_events) - len(cn_events_new) != 0:
            print("not equal 2")
            return
        cn_events_new.sort(key=functools.cmp_to_key(mycmp1))
        cn_events = cn_events_new

    srt = []
    srt_en = []
    srt_cn = []

    for i in range(len(en_events)):
        en = en_events[i]
        cn = cn_events[i]

        fs, fms = divmod(en["tStartMs"], 1000)
        fm, fs = divmod(fs, 60)
        fh, fm = divmod(fm, 60)
        start = "{}:{}:{},{}".format(str(int(fh)).zfill(2), str(int(fm)).zfill(2), str(int(fs)).zfill(2),
                                     str(int(fms)).zfill(3))
        es, ems = divmod(en["tStartMs"] + en["dDurationMs"], 1000)
        em, es = divmod(es, 60)
        eh, em = divmod(em, 60)
        end = "{}:{}:{},{}".format(str(int(eh)).zfill(2), str(int(em)).zfill(2), str(int(es)).zfill(2),
                                   str(int(ems)).zfill(3))

        en_text = en["segs"][0]["utf8"].replace("\n", " ")
        cn_text = cn["segs"][0]["utf8"].replace("\n", " ")
        srt_tmp = f"""{i+1}\n{start} --> {end}\n{en_text}\n{cn_text}\n"""
        srt_tmp_en = f"""{i+1}\n{start} --> {end}\n{en_text}\n"""
        srt_tmp_cn = f"""{i+1}\n{start} --> {end}\n{cn_text}\n"""
        srt.append(srt_tmp)
        srt_en.append(srt_tmp_en)
        srt_cn.append(srt_tmp_cn)

    with open(f"/Users/xinyu.jiang/Desktop/tmp/{id}-en-cn.srt", "w", encoding="utf-8") as f:
        f.write("\n".join(srt))
    with open(f"/Users/xinyu.jiang/Desktop/tmp/{id}-en.srt", "w", encoding="utf-8") as f:
        f.write("\n".join(srt_en))
    with open(f"/Users/xinyu.jiang/Desktop/tmp/{id}-cn.srt", "w", encoding="utf-8") as f:
        f.write("\n".join(srt_cn))

    en_url = f"https://www.ted.com/talks/{name}/transcript.json?language=en"
    en_res = requests.get(en_url, headers=headers)

    en_paragraphs = en_res.json()["paragraphs"]
    en_paragraphs.sort(key=functools.cmp_to_key(cues_cmp1))

    en_list = []
    for en_p in en_paragraphs:
        cues_list = en_p["cues"]
        for c in cues_list:
            en_list.append(c)
    en_list.sort(key=functools.cmp_to_key(cues_cmp2))

    if len(en_list) != len(cn_events_new):
        print("text not equal")

    cn_time_dict = {}
    for h in range(len(en_list)):
        cn_time_dict[en_list[h]["time"]] = cn_events_new[h]["segs"][0]["utf8"]

    c = 0
    for i in range(len(en_paragraphs)):
        cues_en = en_paragraphs[i]["cues"]
        cues_en.sort(key=functools.cmp_to_key(cues_cmp2))

        for cue in cues_en:
            text_ = cue["text"].replace("\n", " ")
            print(text_, end=' ')
            c += 1
        print("")

        for cue in cues_en:
            text_ = cn_time_dict[cue["time"]]
            print(text_, end=' ')
            c += 1
        print("")


if __name__ == "__main__":
    arg1 = sys.argv[1]
    arg2 = sys.argv[2]
    down_load_translate(arg1, arg2)
